package com.cin.cma.server.biz.job;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cin.cma.server.biz.dal.domain.T0100PlaceinfoDO;
import com.cin.cma.server.biz.dal.mapper.T0100PlaceinfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class SessionJob {
    /**
     * 同时执行3个任务的无界线程池
     */
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    @Autowired
    private T0100PlaceinfoMapper t0100PlaceinfoMapper;
    @Autowired
    private SyncService syncService;

    /**
     * 获取要同步的影院信息
     *
     * @return
     */
    private List<T0100PlaceinfoDO> queryPlaceInfoList() {
        QueryWrapper<T0100PlaceinfoDO> placeinfoQueryWrapper = new QueryWrapper<>();
        placeinfoQueryWrapper.lambda().isNotNull(T0100PlaceinfoDO::getCinemalinkid);
        List<T0100PlaceinfoDO> placelist = t0100PlaceinfoMapper.selectList(placeinfoQueryWrapper);
        return placelist;
    }

    /**
     * 同步排期
     */
    @Scheduled(cron = "0 10 * * * ?")
    public void syncSession() {
        log.info("同步排期");
        List<T0100PlaceinfoDO> t0110PlaceInfoList = queryPlaceInfoList();
        for (T0100PlaceinfoDO t0100PlaceInfo : t0110PlaceInfoList) {
            List<DateTime> dateTimeList = DateUtil.rangeToList(new Date(), DateUtil.offsetDay(new Date(), 5), DateField.DAY_OF_YEAR);
            for (DateTime dateTime : dateTimeList) {
                try {
                    syncService.syncSession(t0100PlaceInfo, dateTime);
                } catch (Exception e) {
                    log.error("同步排期异常", e);
                }
            }
        }
    }

    /**
     * 同步座位
     */
    @Scheduled(cron = "0 20 * * * ?")
    public void syncSeat() {
        log.info("同步基础座位");
        List<T0100PlaceinfoDO> t0110PlaceInfoList = queryPlaceInfoList();
        for (T0100PlaceinfoDO t0100PlaceInfo : t0110PlaceInfoList) {
            try {
                syncService.syncSeat(t0100PlaceInfo);
            } catch (Exception e) {
                log.error("同步基础座位", e);
            }
        }
    }
}
